// Package myoffice
// @Author: zhangdi
// @File: convert_image
// @Version: 1.0.0
// @Date: 2023/11/14 21:50
package myoffice

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"
)

// ConvertByLibreoffice 装换文档格式 filePath源文件路径 targetExt目标格式如：pdf outPath输出文件目录，传空字符为当前目录
// 命令示例 ： soffice --headless --invisible --convert-to pdf 合格证.docx
// headless无界面模式 invisible后台执行 --convert-to pdf目标格式 源文件路径
// 注意：需要先安装libreoffice:
// windows安装地址：https://mirrors.cloud.tencent.com/libreoffice/libreoffice/stable/
// windows安装好后项path中把安装路径添加环境变量，默认路径：C:\Program Files\LibreOffice\program
// centos安装方式:sudo yum install libreoffice
func ConvertByLibreoffice(filePath string, targetExt string, outPath string) error {
	var cmd *exec.Cmd
	if runtime.GOOS == "windows" {
		cmd = exec.Command("cmd", "/c", "soffice", "--headless", "--convert-to", targetExt, filePath, "--outdir", outPath)
	} else {
		cmd = exec.Command("soffice", "--headless", "--convert-to", targetExt, filePath, "--outdir", outPath)
	}

	err := cmd.Run()
	if err != nil {
		log.Println(err.Error())
		return fmt.Errorf("ConvertByLibreoffice failed to convert file: %w", err)
	}
	// 添加对 soffice 进程的终止逻辑
	//defer cmd.Process.Kill()
	//if err != nil {
	//	log.Println(err.Error())
	//}
	return nil
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// interactiveToexec
// @Description: 执行指定命令
// @param commandName 命令名称
// @param params 命令参数
// @return string 执行结果返回信息
// @return bool 是否执行成功
func interactiveToexec(commandName string, params []string) (string, bool) {
	cmd := exec.Command(commandName, params...)
	buf, err := cmd.Output()
	w := bytes.NewBuffer(nil)
	cmd.Stderr = w
	if err != nil {
		log.Println("Error: <", err, "> when exec command read out buffer")
		return "", false
	} else {
		return string(buf), true
	}
}
